package dtd.PHS.VND_ExchangeRate.ui.adapters;

import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import dtd.PHS.VND_ExchangeRate.R;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;

public class PreviewSMSAdapter extends BaseAdapter {

	private ArrayList<String> currencies;
	private ArrayList<String> amount;
	private boolean[] checked;

	public PreviewSMSAdapter(Bundle bundle) {
		super();
		initData(bundle);
	}

	private void initData(Bundle bundle) {
		currencies = new ArrayList<String> ();
		amount = new ArrayList<String>();
		for(String curr : bundle.keySet()) {
			String am = bundle.getString(curr);
			currencies.add(curr);
			amount.add(am);
		}
		initCheckedFromHistory();
	}

	private void initCheckedFromHistory() {
		checked = new boolean[amount.size()];
		String choosenCurrencies = Helpers.getPreference(Helpers.PREF_LAST_CHOOSEN_PREVIEW_SMS);
		if ( choosenCurrencies == null) {
			Arrays.fill(checked, true);
		} else {
			Arrays.fill(checked, false);
			String[] words = choosenCurrencies.split(",");
			for(int i = 0 ; i < currencies.size() ; i++) {
				for(int j  = 0 ; j < words.length ; j++)
					if ( words[j].trim().toLowerCase().equals(currencies.get(i).toLowerCase())) {
						checked[i] = true;
						break;
					}
			}
		}
	}

	@Override
	public int getCount() {
		return currencies.size();
	}

	@Override
	public Object getItem(int position) {
		return currencies.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View v = Helpers.inflateView(R.layout.preview_sms_item, null);
		TextView tvCurrency = (TextView) v.findViewById(R.id.tvTitle);
		CheckBox cb = (CheckBox) v.findViewById(R.id.cb);
		tvCurrency.setText(currencies.get(position));
		if ( checked[position] ) 
			cb.setChecked(true);
		else cb.setChecked( false );		
		cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				checked[position] = isChecked;
			}
		});
		return v;
	}
	
	public ArrayList<CurrencyAmountItem> getSelectedItems() {
		ArrayList<CurrencyAmountItem> items = new ArrayList<CurrencyAmountItem>();
		for(int i = 0 ; i < amount.size() ; i++)
			if ( checked[i]) {
				items.add(new CurrencyAmountItem(currencies.get(i),amount.get(i)));
			}
		return items;
	}

}
